package descentFly
{
	import descentFly.away3D4.df_loadSection;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Vector3D;
	
	import org.osmf.media.LoadableElementBase;

	public class df_FData extends EventDispatcher {
		public static const FIELD_CLASS: String = 'Class';
		private var _loaded: int;
		
		public function df_FData() {
			super();
			_loaded = 0;
		}
		
		public function get loaded(): Boolean {
			return _loaded == 0;
		}
		
		protected function doLoadComplete(): void {
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function parseFDArray(aData: Array, aClasses: Object, Reference: Object, ClassesURL: String = ''): Array {
			for (var i:int=0; i<aData.length; i++) {
				aData[i] = parseFDObject(aData[i], aClasses, Reference, ClassesURL)
			}
			return aData;
		}
		
		public function parseFDObject(aData: Object, aClasses: Object, Reference: Object, ClassesURL: String = ''): * {
			if (aData is Array) 
				return parseFDArray(aData as Array, aClasses, Reference, ClassesURL);
			else if (aData is String) {
				if (aData.indexOf('0x') == 0) 
					return parseInt(aData as String, 16);
				else if (Reference.hasOwnProperty(aData)) 
					return Reference[aData];
			} else if (typeof(aData) == 'object') {
				function loadClass(prop: String): void {
					var ls: df_loadSection = new df_loadSection();
					var loader: Loader = ls.addLoader(ClassesURL + aData[prop] + '.swf');
					ls.endSection(function(): void {
						aData[prop] = loader.contentLoaderInfo.applicationDomain.getDefinition(aData[prop]);
						_loaded--;
						if (_loaded == 0) doLoadComplete();
					});
					_loaded++;
				}
				
				var prop: String;
				var props: Array = new Array();
				for (prop in aData) props.push(prop);
				
				for (var i:int=0; i<props.length; i++) {
					prop = props[i];
					if (prop == FIELD_CLASS) {
						if (typeof(aData[prop]) == 'string') {
							if (aClasses.hasOwnProperty(aData[prop]))
								aData[prop] = aClasses[aData[prop]];
							else loadClass(prop);
						}
					} else aData[prop] = parseFDObject(aData[prop], aClasses, Reference, ClassesURL);
				}
			}
			return aData;
		}
		
		public static function parseVector(aData: Object): Vector3D {
			if (aData is String) {
				var a: Array = (aData as String).split(',');
				return new Vector3D(a[0], a[1], a[2]);
			} else return aData as Vector3D;
		}
	}
}